package com.mti.component;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Date;

/**
 * JWTComponent class
 *
 * @author zhaoyj
 * @date 2019/3/12
 */
public class JwcComponent {

    public static final long EXPIRATIONTIME = 432_000_000;     // 5天
    static final String SECRET_KEY = "Dk4ZjZiY2Q0NjIxZDM3M2NhZGU0ZTgzMjYyN2I0ZjS";            // JWT密码
    static final String TOKEN_PREFIX = "Bearer";        // Token前缀
    public static final String HEADER_STRING = "Authorization";// 存放Token的Header Key
    public static final String COOKIE = "Cookie";// 存放Token的Header Key
    public static final String USER_AGENT = "user-agent";
    static final String TOKEN_ISSUER="http://mti-sh.com";


    /**
     * 创建token
     * @param userName
     * @return
     */
    public static String createToken(String userName){
        Date date = new Date();
        date.setTime(date.getTime() + EXPIRATIONTIME);
        Algorithm algorithm = Algorithm.HMAC256(SECRET_KEY);
        return JWT.create().withSubject(userName).withJWTId(userName).withKeyId(userName).withExpiresAt(date).withIssuer(TOKEN_ISSUER).sign(algorithm);
    }

    /**
     *
     * @param token String
     * @return subject
     */
    public static String parseUsername(String token){
        Algorithm algorithm = Algorithm.HMAC256(SECRET_KEY);
        JWTVerifier verifier = JWT.require(algorithm)
                .withIssuer(TOKEN_ISSUER)
                .build(); //Reusable verifier instance
        DecodedJWT jwt = verifier.verify(token);
        String subject = jwt.getSubject();
        return subject;
    }

}
